<template>
  <div class="memo-container">
    <el-card>
      <div slot="header" class="header">
        <span>备忘录</span>
        <el-button type="primary" @click="handleAdd">新增备忘录</el-button>
      </div>

      <el-row :gutter="20">
        <el-col :span="8" v-for="memo in memoList" :key="memo.id">
          <el-card class="memo-card" :body-style="{ padding: '0px' }">
            <div class="memo-header">
              <span class="memo-title">{{ memo.title }}</span>
              <el-tag :type="memo.priority === '高' ? 'danger' : memo.priority === '中' ? 'warning' : 'info'">
                {{ memo.priority }}优先级
              </el-tag>
            </div>
            <div class="memo-content">
              <p class="memo-desc">{{ memo.content }}</p>
              <div class="memo-info">
                <span>截止日期：{{ memo.deadline }}</span>
                <el-tag
                  :type="memo.status === '已完成' ? 'success' : (isAboutToExpire(memo.deadline) ? 'danger' : 'info')"
                >
                  {{ memo.status }}
                </el-tag>
              </div>
            </div>
            <div class="memo-footer">
              <el-button type="text" @click="handleEdit(memo)">编辑</el-button>
              <el-button type="text" @click="handleComplete(memo)" v-if="memo.status === '未完成'">
                完成
              </el-button>
              <el-button type="text" class="delete-btn" @click="handleDelete(memo)">删除</el-button>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </el-card>

    <!-- 新增/编辑对话框 -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="500px">
      <el-form :model="memoForm" :rules="rules" ref="memoForm" label-width="100px">
        <el-form-item label="标题" prop="title">
          <el-input v-model="memoForm.title"></el-input>
        </el-form-item>
        <el-form-item label="内容" prop="content">
          <el-input type="textarea" v-model="memoForm.content" :rows="4"></el-input>
        </el-form-item>
        <el-form-item label="优先级" prop="priority">
          <el-select v-model="memoForm.priority" placeholder="请选择优先级">
            <el-option label="高" value="高"></el-option>
            <el-option label="中" value="中"></el-option>
            <el-option label="低" value="低"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="截止日期" prop="deadline">
          <el-date-picker
            v-model="memoForm.deadline"
            type="datetime"
            placeholder="选择日期时间"
            value-format="yyyy-MM-dd HH:mm:ss"
            :disabled-date="disabledDate"
            @change="handleDateChange"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="memoForm.status" placeholder="请选择状态">
            <el-option label="未完成" value="未完成"></el-option>
            <el-option label="已完成" value="已完成"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'Memo',
  data() {
    return {
      memoList: [],
      dialogVisible: false,
      dialogTitle: '新增备忘录',
      memoForm: {
        title: '',
        content: '',
        priority: '中',
        deadline: null,
        status: '未完成'
      },
      rules: {
        title: [
          { required: true, message: '请输入标题', trigger: 'blur' }
        ],
        content: [
          { required: true, message: '请输入内容', trigger: 'blur' }
        ],
        priority: [
          { required: true, message: '请选择优先级', trigger: 'change' }
        ],
        deadline: [
          { required: true, message: '请选择截止日期', trigger: 'change' }
        ],
        status: [
          { required: true, message: '请选择状态', trigger: 'change' }
        ]
      }
    }
  },
  created() {
    this.fetchMemoList()
  },
  methods: {
    async fetchMemoList() {
      try {
        const response = await this.$http.get('/note/list')
        if (response.data.code === 20000) {
          this.memoList = response.data.data.rows || []
        } else {
          throw new Error(response.data.message || '获取备忘录列表失败')
        }
      } catch (error) {
        console.error('Fetch memo list error:', error)
        this.$message.error('获取备忘录列表失败')
      }
    },
    handleAdd() {
      this.dialogTitle = '新增备忘录'
      this.memoForm = {
        title: '',
        content: '',
        priority: '中',
        deadline: null,
        status: '未完成'
      }
      this.dialogVisible = true
    },
    handleEdit(memo) {
      this.dialogTitle = '编辑备忘录'
      this.memoForm = { ...memo }
      if (typeof this.memoForm.deadline === 'number') {
        this.memoForm.deadline = this.formatDateTime(this.memoForm.deadline)
      } else if (typeof this.memoForm.deadline === 'string' && this.memoForm.deadline.includes('T')) {
        this.memoForm.deadline = this.formatDateTime(new Date(this.memoForm.deadline).getTime())
      }
      this.dialogVisible = true
    },
    formatDateTime(ts) {
      const date = new Date(ts)
      const pad = n => n < 10 ? '0' + n : n
      return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())} ${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}`
    },
    async handleComplete(memo) {
      try {
        const response = await this.$http.put('/note', {
          ...memo,
          status: '已完成'
        })
        if (response.data.code === 20000) {
          this.$message.success('操作成功')
          this.fetchMemoList()
        } else {
          throw new Error(response.data.message || '操作失败')
        }
      } catch (error) {
        console.error('Complete memo error:', error)
        this.$message.error('操作失败')
      }
    },
    async handleDelete(memo) {
      try {
        await this.$confirm('确认删除该备忘录吗？', '提示', {
          type: 'warning'
        })
        const response = await this.$http.delete(`/note/${memo.id}`)
        if (response.data.code === 20000) {
          this.$message.success('删除成功')
          this.fetchMemoList()
        } else {
          throw new Error(response.data.message || '删除失败')
        }
      } catch (error) {
        if (error !== 'cancel') {
          console.error('Delete memo error:', error)
          this.$message.error('删除失败')
        }
      }
    },
    submitForm() {
      this.$refs.memoForm.validate(async valid => {
        if (valid) {
          const memoData = {
            id: this.memoForm.id,
            title: this.memoForm.title,
            content: this.memoForm.content,
            priority: this.memoForm.priority,
            deadline: this.memoForm.deadline ? this.memoForm.deadline.replace(' ', 'T') : null,
            status: this.memoForm.status
          }
          console.log('提交数据', memoData)
          try {
            let response
            if (this.memoForm.id) {
              response = await this.$http.put('/note', memoData)
            } else {
              response = await this.$http.post('/note', memoData)
            }
            if (response.data.code === 20000) {
              this.$message.success('保存成功')
              this.dialogVisible = false
              this.fetchMemoList()
            } else {
              throw new Error(response.data.message || '保存失败')
            }
          } catch (error) {
            console.error('Save memo error:', error)
            this.$message.error('保存失败')
          }
        }
      })
    },
    isAboutToExpire(deadline) {
      if (!deadline) return false;
      const now = new Date();
      const end = new Date(deadline);
      return (end - now) <= 24 * 60 * 60 * 1000 && (end - now) > 0;
    },
    handleDateChange() {
      this.$nextTick(() => {
        this.fetchMemoList()
      })
    },
    disabledDate(date) {
      return date < new Date(new Date().setHours(0, 0, 0, 0));
    }
  }
}
</script>

<style scoped>
.memo-container {
  padding: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.memo-card {
  margin-bottom: 20px;
}

.memo-header {
  padding: 14px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-bottom: 1px solid #ebeef5;
}

.memo-title {
  font-size: 16px;
  font-weight: bold;
}

.memo-content {
  padding: 14px;
}

.memo-desc {
  margin-bottom: 10px;
  color: #606266;
  min-height: 60px;
}

.memo-info {
  display: flex;
  justify-content: space-between;
  color: #909399;
  font-size: 14px;
}

.memo-footer {
  padding: 14px;
  border-top: 1px solid #ebeef5;
  display: flex;
  justify-content: flex-end;
}

.delete-btn {
  color: #F56C6C;
}
</style> 